package com.niit.mobileDevide.batterydrain;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.IOException;

public class BatteryDrainMapper extends Mapper<LongWritable, Text, Text, BatteryDrainBean> {

    private static final int BATTERY_DRAIN_INDEX = 5; // 电池消耗索引
    private static final int OPERATING_SYSTEM_INDEX = 2; // 操作系统索引

    @Override
    protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        if (key.get() == 0) return; // 忽略标题行

        String[] columns = value.toString().split(",");
        if (columns.length < 8) { // 确保至少有8个字段（假设操作系统在第3列）
            System.err.println("Skipping line due to insufficient fields: " + value);
            return;
        }

        try {
            // 提取电池消耗
            String batteryDrainStr = columns[BATTERY_DRAIN_INDEX].trim();
            double batteryDrain;

            try {
                // 将电池消耗字符串转换为双精度浮点数
                batteryDrain = Double.parseDouble(batteryDrainStr);
            } catch (NumberFormatException e) {
                System.err.println("Invalid battery drain format: " + batteryDrainStr + ". Skipping line.");
                return;
            }

            // 只处理电池消耗大于2000mAh的记录
            if (batteryDrain <= 2000) {
                return;
            }

            // 提取操作系统类型
            String operatingSystemStr = columns[OPERATING_SYSTEM_INDEX].trim();
            int operatingSystem;

            try {
                // 将操作系统字符串转换为整数
                operatingSystem = Integer.parseInt(operatingSystemStr);
            } catch (NumberFormatException e) {
                System.err.println("Invalid operating system format: " + operatingSystemStr + ". Skipping line.");
                return;
            }

            // 写入键值对，键为操作系统类型，值为计数1
            context.write(new Text(String.valueOf(operatingSystem)), new BatteryDrainBean(1));
        } catch (NumberFormatException e) {
            // 跳过格式错误的行，并打印错误信息
            System.err.println("Error parsing line: " + value + ". Error: " + e.getMessage());
        }
    }
}